/*
 * 	Flan.Zeng 2011-2016	http://git.oschina.net/signup?inviter=flan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.flan.study.java.nio;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 测试NIO写入文件数据, 步骤：
 * 1.从FileInputStream获取Channel 
 * 2.创建Buffer
 * 3.将数据从Channel写入到Buffer中
 * @author flan
 * @date   2015年12月17日
 */
public class TestNioWriteFile {
	
	static private final byte message[] = { 83, 111, 109, 101, 32,  
	        98, 121, 116, 101, 115, 46 }; 
	
	public static void main(String[] args) throws Exception {
		
		FileOutputStream fos = new FileOutputStream("E:/nio/write.txt");
		
		// 获取通道
		FileChannel channel = fos.getChannel();
		
		// 创建缓冲区 
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		
		// 向buffer中插入数据
		//buffer.put(message);
		for(byte b : message){
			buffer.put(b);
			System.out.println((char)b);
		}
		
		// 将buffer由读取类型改为写入类型,必须调用
		buffer.flip();
		
		channel.write(buffer);
		
		fos.close();
	}
	
}
